package com.oa.core.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.oa.admin.entity.EmpBenefitsRemind;
import com.oa.admin.entity.FinancialRemind;
import com.oa.admin.entity.SubsidyRemind;
import com.oa.admin.service.IEmpBenefitsRemindService;
import com.oa.admin.service.IFinancialRemindService;
import com.oa.admin.service.ISubsidyRemindService;
import com.oa.core.utils.SendMsgManager;
import com.oa.system.entity.User;
import com.oa.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class RemindTask {

    @Autowired
    private IEmpBenefitsRemindService empBenefitsRemindService;

    @Autowired
    private IFinancialRemindService financialRemindService;

    @Autowired
    private ISubsidyRemindService subsidyRemindService;

    @Autowired
    private SendMsgManager sendMsgManager;

    @Autowired
    private IUserService userService;

    @Scheduled(cron = "0 0 * * * ? ")
    public void dayRemind() {
        System.out.println("发送提醒当前时间" + new Date());

        Wrapper wrapper = new EntityWrapper().where("DATE_FORMAT(remind_time, '%Y-%M-%d %H') = DATE_FORMAT({0}, '%Y-%M-%d %H')", new Date());
        List<EmpBenefitsRemind> empBenefitsReminds = empBenefitsRemindService.selectList(wrapper);

        empBenefitsReminds.forEach(d -> {
            String[] userIds = d.getAlertOthers().split(",");
            for (String userId : userIds) {
                User user = userService.selectById(userId);
                sendMsgManager.sendMsg(user, "员工福利提醒", JSON.toJSONString(d));
            }
        });

        List<FinancialRemind> financialReminds = financialRemindService.selectList(wrapper);

        financialReminds.forEach(d -> {
            String[] userIds = d.getAlertOthers().split(",");
            for (String userId : userIds) {
                User user = userService.selectById(userId);
                sendMsgManager.sendMsg(user, "财务事项提醒", JSON.toJSONString(d));
            }
        });

        wrapper = new EntityWrapper().where("DATE_FORMAT(arrival_time, '%Y-%M-%d %H') = DATE_FORMAT({0}, '%Y-%M-%d %H')", new Date());

        List<SubsidyRemind> subsidyReminds = subsidyRemindService.selectList(wrapper);

        subsidyReminds.forEach(d -> {
            String[] userIds = d.getAlertOthers().split(",");
            for (String userId : userIds) {
                User user = userService.selectById(userId);
                sendMsgManager.sendMsg(user, "补贴提醒", JSON.toJSONString(d));
            }
        });
    }
}
